package com.xjm.api.web;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xjm.entity.model.AddressesModel;
import com.xjm.entity.vo.Result;
import com.xjm.service.IAddressesService;
import com.xjm.utils.UserContext;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user/address")
@RequiredArgsConstructor
public class WebAddressController {
    private final IAddressesService addressesService;

    @GetMapping
    public Result<List<AddressesModel>> getAddresses() {
        Integer userId = UserContext.getUserId();
        LambdaQueryWrapper<AddressesModel> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AddressesModel::getUserId, userId);
        List<AddressesModel> list = addressesService.list(wrapper);
        list.forEach(addressesModel -> {
            addressesModel.setRegion(JSONUtil.parseArray(addressesModel.getRegion()));
        });
        return Result.success(list);
    }

    @PostMapping
    public Result<AddressesModel> saveOrUpdate(@RequestBody AddressesModel addressesModel) {
        Integer isDefault = addressesModel.getIsDefault();
        if (isDefault != null && isDefault == 1) {
            LambdaQueryWrapper<AddressesModel> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(AddressesModel::getUserId, UserContext.getUserId());
            wrapper.eq(AddressesModel::getIsDefault, 1);
            AddressesModel addressesModel1 = addressesService.getOne(wrapper);
            if (addressesModel1 != null) {
                addressesModel1.setIsDefault(0);
                addressesService.updateById(addressesModel1);
            }
        }
        addressesModel.setUserId(UserContext.getUserId());
        addressesModel.setRegion(JSONUtil.toJsonStr(addressesModel.getRegion()));
        addressesService.saveOrUpdate(addressesModel);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result<Void> delete(@PathVariable String id) {
        addressesService.removeById(id);
        return Result.success();
    }
}
